package org.brownflat.lighthouse.web;


import org.apache.log4j.Logger;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

public class PropertyPlaceholder extends PropertyPlaceholderConfigurer {

	private static final Logger LOG = Logger.getLogger(PropertyPlaceholder.class);
    private Properties properties;

    public PropertyPlaceholder() {
		try {
			loadPropertiesFromHome();
		} catch (Exception e) {
			LOG.error(e);
		}

        if(properties == null) {
            throw new RuntimeException(String.format("No properties configuration available"));
        }
	}

	protected String resolvePlaceholder(String placeholder, Properties props) {
    	String value = properties.getProperty(placeholder);
	    LOG.info(String.format("Loading property [%s] with [%s].", placeholder, value));
		return value;
	}

    private void loadPropertiesFromHome() throws IOException {
        String home = System.getenv("LIGHTHOUSE_HOME");
        FileReader fileReader = new FileReader(home + "/lighthouse.properties");
        if(fileReader != null) {
            LOG.info("Loading default configuration properties");
            properties = new Properties();
            properties.load(fileReader);
        } else {
            throw new RuntimeException("Could not find default properties file");
        }
    }
}
